/**
 * 计算2数字的数学计算值，防止js浮点数精度问题
 * @param {*} n1 数字1
 * @param {*} n2 数字2
 * @param {*} mathSymbol 数学符号 + - * /
 * @returns {number}
 */
let calculation = (n1, mathSymbol, n2) => {
  let result = ''
  // 转换为数字
  n1 = parseFloat(n1)
  n2 = parseFloat(n2)
  if (isNaN(n1) && isNaN(n2)) {
    return result
  }
  if (isNaN(n1)) {
    result = n2
    return result
  }
  if (isNaN(n2)) {
    result = n1
    return result
  }
  if (!mathSymbol) {
    mathSymbol = '+'
  }
  if (mathSymbol == '+') {
    result = calulateAdd(n1, n2)
  } else if (mathSymbol == '-') {
    result = calulateReduce(n1, n2)
  } else if (mathSymbol == '*' || mathSymbol == 'x') {
    result = precisionX(n1, n2)
  } else if (mathSymbol == '/' || mathSymbol == '÷') {
    result = precisionDiv(n1, n2)
  }
  return result
}

/**
 * 两数相加
 * @param {*} n1 数字1
 * @param {*} n2 数字2
 */
let calulateAdd = (n1, n2) => {
  let m = 0
  let m1 = 0
  let m2 = 0
  let s1 = n1.toString()
  let s2 = n2.toString()
  try {
    m1 = s1.split('.')[1].length
  } catch (e) {}
  try {
    m2 = s2.split('.')[1].length
  } catch (e) {}
  m = Math.pow(10, Math.max(m1, m2))
  return ((Number(n1 * m) + Number(n2 * m)) / m)
}

/**
 * 两数相减
 * @param {*} n1 数字1
 * @param {*} n2 数字2
 */
let calulateReduce = (n1, n2) => {
  let m = 0
  let m1 = 0
  let m2 = 0
  let s1 = n1.toString()
  let s2 = n2.toString()
  try {
    m1 = s1.split('.')[1].length
  } catch (e) {}
  try {
    m2 = s2.split('.')[1].length
  } catch (e) {}
  m = Math.pow(10, Math.max(m1, m2))
  return ((Number(n1 * m) - Number(n2 * m)) / m)
}

/**
 * 两数相乘
 * @param {*} n1 数字1
 * @param {*} n2 数字2
 */
let precisionX = (n1, n2) => {
  let m = 0
  let s1 = n1.toString()
  let s2 = n2.toString()
  try {
    m += s1.split(".")[1].length
  } catch (e) {}
  try {
    m += s2.split(".")[1].length
  } catch (e) {}
  return (Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m))
}

/**
 * 两数相除
 * @param {*} n1 数字1
 * @param {*} n2 数字2
 */
let precisionDiv = (n1, n2) => {
  let m1 = 0
  let m2 = 0
  let s1 = n1.toString()
  let s2 = n2.toString()
  try {
    m1 = s1.split(".")[1].length
  } catch (e) {}
  try {
    m2 = s2.split(".")[1].length
  } catch (e) {}
  return (Number(s1.replace(".", "")) / Number(s2.replace(".", "")) * Math.pow(10, m2 - m1))
}

/**
 * 两数取余
 * @param {*} n1 数字1
 * @param {*} n2 数字2
 */
let calulateModular = (n1, n2) => {
  let m = 0
  let m1 = 0
  let m2 = 0
  let s1 = n1.toString()
  let s2 = n2.toString()
  try {
    m1 = s1.split(".")[1].length
  } catch (e) {}
  try {
    m2 = s2.split(".")[1].length
  } catch (e) {}
  m = Math.max(m1, m2)
  m = Math.pow(10, m)
  return precisionDiv(precisionX(n1, m) % precisionX(n2, m), m)
}

export {
  calculation,
  calulateAdd,
  calulateReduce,
  calulateModular,
  precisionDiv,
  precisionX
}